package com.jeesite.modules.stock.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jeesite.common.entity.Page;
import com.jeesite.modules.stock.dao.GroupDailyDataDao;
import com.jeesite.modules.stock.dto.SectorDateRangeRankSearchDTO;
import com.jeesite.modules.stock.dto.SectorSearchDTO;
import com.jeesite.modules.stock.dto.vo.StockHistoryDataVO;

@Service
public class SectorDailyService extends AbstractStockService{
	
	@Autowired
	private GroupDailyDataDao groupDailyDataDao;
	
	/**
	 * 分页查询板块数据
	 * 
	 * @param searchDTO 查询参数
	 * @return
	 */
	public Page<Map<String, Object>> findPage(SectorSearchDTO searchDTO) {
		return groupDailyDataDao.findPage(searchDTO);
	}
	
	/**
	 * 板块区间排名
	 * 
	 * @param searchDTO 查询参数
	 * @return
	 */
	public Page<StockHistoryDataVO> findDateRangeRank(SectorDateRangeRankSearchDTO searchDTO) {

		String[] sortedDate = sortBeginAndEndTime(searchDTO.getStartDate(), searchDTO.getEndDate(), "yyyy-MM-dd");
		searchDTO.setStartDate(sortedDate[0]);
		searchDTO.setEndDate(sortedDate[1]);
		
		searchDTO.setStartDate(getKaipanDateOfStart(searchDTO.getStartDate(), 1));
		searchDTO.setEndDate(getKaipanDateOfStart(searchDTO.getEndDate(), -1));
		if(searchDTO.getStartDate().equals(searchDTO.getEndDate())) {
			String startDate = DateFormat.formatDate(DateFormat.dayPlus(DateFormat.parseDate(searchDTO.getStartDate()), -1));
			searchDTO.setStartDate(getKaipanDateOfStart(startDate, -1));
		}
		
		Page<Map<String, Object>> page = groupDailyDataDao.findDateRangeRank(searchDTO);
		
		Page<StockHistoryDataVO> pageVr = new Page<StockHistoryDataVO>(page.getPageNo(), page.getPageSize());
		pageVr.setCount(page.getCount());
		
		if(page.getList()!=null) {
			List<StockHistoryDataVO> list = new ArrayList<StockHistoryDataVO>();
			page.getList().forEach(item->{
				StockHistoryDataVO vo = new StockHistoryDataVO();
				vo.setId(Integer.parseInt(item.get("id").toString()));
				vo.setName(String.valueOf(item.get("groupName")));
				vo.setClose(item.get("close")==null?0:Double.parseDouble(item.get("close").toString()));
				vo.setRiseAndFall(item.get("riseAndFall")==null?0:Double.parseDouble(item.get("riseAndFall").toString()));
				vo.setRiseAndFall(BigDecimal.valueOf(vo.getRiseAndFall()).setScale(2, RoundingMode.HALF_UP).doubleValue());
				list.add(vo);
			});
			pageVr.setList(list);
		}
		return pageVr;
	}

}
